package top.wangjiu.java.jvm.constantinfo.refrence;

import top.wangjiu.java.jvm.constantinfo.ConstantPoolInfo;
import top.wangjiu.java.jvm.constantinfo.SymbolicReferenceConstantPoolInfo;

/**
 * @ClassName NameAndTypeInfo
 * @Description
 * CONSTANT_NameAndType_info {
 *     u1 tag;
 *     u2 name_index; //name_index 项的值必须是对常量池的有效索引， 常量池在该索引处的项必须是
 *     CONSTANT_Utf8_info结构，这个结构要么表示特殊的方法名<init>，要么表示一个有效
 *     的字段或方法的非限定名（ Unqualified Name）。
 *     u2 descriptor_index;//descriptor_index 项的值必须是对常量池的有效索引， 常量池在该索引
 *     处的项必须是CONSTANT_Utf8_info结构。
 * }
 * @Author wangjiu
 * @Date 2022/1/14 11:56 上午
 */
public class NameAndTypeCPInfo extends SymbolicReferenceConstantPoolInfo {

    public final static short TAG = 12;
    public final static short INFO_LENGTH = 4;
    private final short index;

    private final short nameIndex;

    private final short descriptorIndex;

    public NameAndTypeCPInfo(byte[] bytes, short index){
        this.index = index;
        nameIndex = (short)(bytes[0] << 8 | bytes[1]);
        descriptorIndex = (short)(bytes[2] << 8 | bytes[3]);
    }

    @Override
    public short tag() {
        return TAG;
    }

    @Override
    public short index() {
        return index;
    }

    @Override
    public short infoLength() {
        return INFO_LENGTH;
    }

    @Override
    public String toFullString(ConstantPoolInfo[] poolInfos) {
        return "#"+index +" = NameAndType" + "\t#"+nameIndex +":#"+ descriptorIndex+ "\t\t// "+poolInfos[nameIndex].toString(poolInfos) + ":"+poolInfos[descriptorIndex].toString(poolInfos);
    }

    @Override
    public String toString(ConstantPoolInfo[] poolInfos) {
        return poolInfos[nameIndex].toString(poolInfos) + ":"+poolInfos[descriptorIndex].toString(poolInfos);
    }
}
